package spa_data;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;

public class Database {
	//Datastructure
	private HashMap<Class<? extends Mammal>, ArrayList<Mammal>> database;
	
	//Constructor
	public Database(){
		database = new HashMap<Class<? extends Mammal>, ArrayList<Mammal>>();
	}
	
	//Methods
	public void add(Mammal animal){
		if(!database.containsKey(animal.getClass()))
		{
			ArrayList<Mammal> animalArray = new ArrayList<Mammal>();
			animalArray.add(animal);
			database.put(animal.getClass(), animalArray);
		}
		else{
		database.get(animal.getClass()).add(animal);
		}
		
	}
	
	public Mammal find(String name) throws IllegalMammalException
	{
			for (ArrayList<Mammal> all : database.values()) 
			{
			for (Mammal m : all) {
				if(name.equals(m.getName()))
					{
					return m;
					}
			}		
			}
			throw new IllegalMammalException(name+" not found");
	}
	
	public void spot(String name){
	try{
		find(name).sighted();
	}
	catch (IllegalMammalException e){
		System.out.println(e.information);
	}

	}
	
	public int getCount(Class<? extends Mammal> MammalType){
		int i=0;
		for(Mammal all:database.get(MammalType))
			{
			i+=all.sightings();
			}
		return i;
	}
	
	public void save(String filename) throws IOException{
		PrintWriter out = new PrintWriter(filename+".txt");
		out.println("SPA observations");
		for (ArrayList<Mammal> all : database.values()){ 
		out.println();
		out.println("Species: "+all.get(0).getClass().toString().substring(15)+"\tTotal sightings :"
		+this.getCount(all.get(0).getClass()));	
		for (Mammal m : all) {
		out.println(m.toString());
		}
		}
		out.close();
	}
			
	

}
